<template>
  <el-popover :visible="visible" placement="bottom-start" :width="600">
    <template #reference>
      <div class="search-item" :class="{ active: visible }" @click="visible = !visible">
        <span class="label">更多筛选</span>
        <img src="~img/filter.png" width="10" class="ml5">
      </div>
    </template>

    <SchemaForm
      ref="setSchemaFormRef"
      :fields="fields"
      :form-schema="selectorOption"
      class="pt6"
    >
      <template v-for="item in filterSlot" :key="item.slotName" #[item.slotName]>
        <slot :name="item.slotName" />
      </template>
    </SchemaForm>

    <div class="search-footer">
      <el-button :auto-insert-space="false" @click="visible = false">取消</el-button>
      <el-button :auto-insert-space="false" @click="clear">清空</el-button>
      <el-button :auto-insert-space="false" type="primary" @click="search">筛选</el-button>
    </div>
  </el-popover>
</template>

<script setup>
import { computed } from 'vue'
import { deepClone } from '@/util'
import { isUndefined } from 'lodash-es'

const emit = defineEmits(['toggle', 'confirm', 'update:fields', 'resetMore'])
const props = defineProps({
  fields: {
    type: Object
  },
  formSchema: {
    type: Array,
    default() {
      return []
    }
  },
  defaultForm: {
    type: Object,
    default() {
      return {}
    }
  }
})

const visible = ref(false)
const setSchemaFormRef = ref(null)

const isUnfold = ref(!props.unfold)

const selectorOption = computed(() => {
  const temp = deepClone(props.formSchema).map(item => {
    item.props.labelWidth = item.props.labelWidth || '70px'
    if (!isUndefined(item.hidden)) {
      item.hidden = !isUnfold.value
    }
    return item
  })

  return [
    ...temp
  ]
})

const filterSlot = computed(() => {
  return props.formSchema.filter(item => item.type === 'slot')
})

const search = () => {
  emit('confirm', { type: 'confirm', data: props.fields })
  visible.value = false
}

const clear = () => {
  const obj = {}
  props.formSchema.forEach(item => {
    if (Array.isArray(item.field)) {
      item.field.forEach(v => {
        obj[v] = ''
      })
    } else {
      obj[item.field] = ''
    }
  })
  emit('resetMore', obj)
  // setTimeout(() => {
  //   emit('confirm', { type: 'reset', data: props.fields })
  // }, 100)
  visible.value = false
}

function close() {
  visible.value = false
}

defineExpose({
  search,
  clear,
  close
})
</script>

<style scoped lang="scss">
@import "./modules/search";
.search-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
}
</style>
